package org.gc.webapp.action.login;

import javax.servlet.http.HttpSession;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.gc.webapp.action.BaseAction;
import org.springframework.security.DisabledException;
import org.springframework.security.ui.AbstractProcessingFilter;


@Results({
	  @Result(name="success", location="login.jsp"),
	  @Result(name="adminLogin", type="redirect" ,params = {"location", "/admin/login.do?error=true" })
	})

public class LoginAction extends BaseAction {

	private static final long serialVersionUID = 350428000111684699L;

	private boolean error;

	private String errorMessage;
	
	private String loginUrl ; 
	
	public LoginAction(){
		setLoginUrl("/login/login.do");
	}
	
	protected String jumpToAdmin(){
		String url = (String)getRequest().getSession().getAttribute("login_url");
		if(url!=null && url.indexOf("/admin/login.do")>-1){
			return "adminLogin";
		}
		return null;

	}

	public String execute() {
		
		HttpSession session =  getRequest().getSession();
		
		if (error) {
			
			String jump = jumpToAdmin();
			if(jump!=null){
				return jump;
			}
			 
			Exception ex = (Exception) getRequest()
					.getSession().getAttribute(
							AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY);

			if (ex != null) {
				if (ex instanceof DisabledException) {
					errorMessage = "用户已被禁用.";
				} else {
					errorMessage = "用户名或密码不正确.";
				}
			}
		}else{
			session.setAttribute("login_url", this.getLoginUrl());
		}
		
		return SUCCESS;
	}

	public void setError(boolean error) {
		this.error = error;
	}

	public boolean isError() {
		return error;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

	public String getLoginUrl() {
		return loginUrl;
	}
}
